package com.zgh.zhongcan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgh.zhongcan.common.BaseContext;
import com.zgh.zhongcan.common.R;
import com.zgh.zhongcan.entity.Category;
import com.zgh.zhongcan.entity.Employee;
import com.zgh.zhongcan.entity.Orders;
import com.zgh.zhongcan.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 获取用户订单
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(int page,int pageSize){
        //构造分页构造器，设置分页条件
        Page pageInfo=new Page(page,pageSize);
        //根据当前用户id查订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        Long userId = BaseContext.getCurrentId();
        queryWrapper.like(Orders::getUserId,userId );
        //添加排序条件,根据创建时间排序
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        orderService.page(pageInfo,queryWrapper);//会自动给Page对象的属性都赋值,即pageInfo

        return R.success(pageInfo);
    }

    /**
     * 展示所有订单数据
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> pageAll(int page, int pageSize, String beginTime, String endTime){
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        //添加时间条件
        if (beginTime!=null && endTime!=null){queryWrapper.between(Orders::getOrderTime,beginTime,endTime);}
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //分页查询
        orderService.page(pageInfo,queryWrapper);
        return  R.success(pageInfo);
    }
}